package com.cloud.config;


import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

@Slf4j
public class UserShardingConfig implements PreciseShardingAlgorithm<String> {
    private int TABLE_SIZE = 2;
//    private String TABLE_NAME = "user_";

    /**
     * aop 代理数据源 改写sql语句
     *
     * @param collection
     * @param preciseShardingValue
     * @return
     */
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<String> preciseShardingValue) {
        //preciseShardingValue.getValue() 获取到 sql where 条件的分片字段 id=1
        System.out.println(preciseShardingValue.getValue().hashCode());
        String temp = String.valueOf(preciseShardingValue.getValue().hashCode() % TABLE_SIZE);
        String no = "0" + temp;
        for (String name : collection) {
            if (name.contains(no)) {
                log.info("<tableName:{}>", name);
                return name;
            }
        }
        return null;
    }
}